package com.bdqn.tour.servlet.Hzy;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.bdqn.tour.service.impl.HzyOrdersServiceImpl;
import com.bdqn.tour.util.HzyAliPay.AlipayConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@WebServlet("/alipay/payReturn")
public class PayReturnServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = req.getParameterMap();

        // 获取交易编号
        String tradeNo = req.getParameter("trade_no");
        System.out.println("支付宝返回的交易编号：" + tradeNo);

        // 处理参数
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            // 乱码解决
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        try {
            boolean verifyResult = AlipaySignature.rsaCheckV1(params,
                    AlipayConfig.ALIPAY_PUBLIC_KEY,
                    AlipayConfig.CHARSET,
                    "RSA2");

            String redirectUrl = req.getContextPath() + "/My_fellow_traveler.jsp?payment=";

            // 打印所有参数，用于调试
            System.out.println("收到的所有参数：");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }

            if (verifyResult) {
                String outTradeNo = params.get("out_trade_no");
                String tradeStatus = params.get("trade_status");
                if (tradeStatus == null) {
                    tradeStatus = params.get("trade_state");
                }

                System.out.println("订单号: " + outTradeNo);
                System.out.println("交易状态: " + tradeStatus);

                // 修改：检查订单号格式
                if (outTradeNo != null && outTradeNo.startsWith("H")) {
                    String orderId = outTradeNo.substring(1);
                    System.out.println("提取的订单ID: " + orderId);

                    // 直接尝试更新订单状态
                    HzyOrdersServiceImpl orderService = new HzyOrdersServiceImpl();
                    boolean updated = orderService.updateHotelPayStatus(orderId, "已支付");

                    System.out.println("订单状态更新结果: " + updated);

                    if (updated) {
                        redirectUrl += "success";
                    } else {
                        redirectUrl += "error";
                        System.out.println("更新订单状态失败");
                    }
                } else {
                    redirectUrl += "error";
                    System.out.println("无效的订单号格式");
                }
            } else {
                redirectUrl += "invalid";
                System.out.println("签名验证失败");
            }

            System.out.println("重定向到: " + redirectUrl);
            resp.sendRedirect(redirectUrl);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("处理支付返回时发生异常: " + e.getMessage());
            resp.sendRedirect(req.getContextPath() + "/My_fellow_traveler.jsp?payment=error");
        }
    }
}
